"use strict";
const config = require("../config/server");
const idcServer = config.idcServer;
const vendorKey = config.vendorKey;
const send = require("./send").send;
const suiteDao = require("../dao/suite_dao");
const suiteToOrgDao = require("../dao/suite_to_org_dao");
const getSuiteToken = function(param) {
	console.log("供应商申请 suite token");
	if (!param || !param.suiteKey || !param.suiteSecret || !param.suiteTicket) {
		console.error("参数错误", param);
		return Promise.reject(new Error("e_params"));
	}
	const option = {
		method: "post",
		json: true,
		url: `${idcServer}/isv/access-token`,
		body: {
			vendor_key: vendorKey,
			suite_key: param.suiteKey,
			suite_secret: param.suiteSecret,
			suite_ticket: param.suiteTicket
		}
	};
	return send(option).then(result => result.access_token);
};


const validateUserTicket = function(userTicket) {
	//供应商申请suite token：（凭借供应商的vendor key ，1中取得的ticket和    ssuite的key和secret去申请）
	const suite = this;
	if (!suite.suiteKey || !suite.suiteSecret || !suite.suiteTicket) {
		console.error("suite信息不完整，无法申请suite token");
		throw new Error("e_no_detail");
	}
	const validateUserTicketFromBoss = function(token) {
		console.log("验证用户ticket");
		const option = {
			method: "post",
			json: true,
			url: `${idcServer}/isv/ticket-validation?access_token=${token}`,
			body: {
				suite_key: suite.suiteKey,
				domain_id: suite.domainId,
				user_ticket: userTicket
			}
		};
		return send(option);
	};

	return getSuiteToken(suite).then(validateUserTicketFromBoss);
};



const getPermanentCode = function(suite) {
	//供应商申请suite token：（凭借供应商的vendor key ，1中取得的ticket和    ssuite的key和secret去申请）
	let token;
	const getPermanentCodeFromBoss = function() {
		const option = {
			method: "post",
			json: true,
			url: `${idcServer}/isv/permanent-code?access_token=${token}`,
			body: {
				suite_key: suite.suiteKey,
				tmp_auth_code: suite.tempAuthCode
			}
		};
		console.log("兑换永久授权码");
		return send(option).then(result => suite.permanentCode = result.permanent_code);
	};


	const updatePermanentCode = function() {
		console.log("更新新获取的永久码");
		const ctx = {
			domainId: suite.domainId,
			orgId: suite.orgId
		};
		return suiteToOrgDao.updatePermanentCodeBySuiteKey.call(ctx, suite.suiteKey, suite.permanentCode);
	};
	const activeSuiteFromBoss = function(suite) { //兑换完永久码后必须激活app
		console.log("激活套件");
		const option = {
			method: "post",
			json: true,
			url: `${idcServer}/isv/suite-activation?access_token=${token}`,
			body: {
				suite_key: suite.suiteKey,
				permanent_code: suite.permanentCode
			}
		};
		return send(option);
	};
	return getSuiteToken(suite)
		.then(suiteToken => token = suiteToken)
		.then(getPermanentCodeFromBoss)
		.then(updatePermanentCode)
		.then(activeSuiteFromBoss.bind({}, suite))
		.then(() => suite.permanentCode);
};

const getContact = function(suite, permanentCode) {
	const getContactFromBoss = function(token) {
		const option = {
			method: "post",
			json: true,
			url: `${idcServer}/isv/access-api-token?access_token=${token}`,
			body: {
				suite_key: suite.suiteKey,
				permanent_code: permanentCode,
				domain_id: suite.domainId,
				org_code: suite.orgId
			}
		};
		return send(option);
	};
	console.log("获取用户后台api和token");
	return getSuiteToken(suite).then(getContactFromBoss);
};
/*### 申请直接访问API的token

> http://172.16.1.25:8000/isv/access-api-token?access_token={access_token}

* 请求调用方式: POST

```
{
    "suite_key": "jfwjfpwjfpwjf", 
    "permanent_code": "28103801fw",
    "domain_id": "atwork",
    "org_code": "jdqojdq"
}
```

* 响应
```
{
    "status": 0, 
    "message": "Everything is ok.", 
    "result": {
        "api_access_token": "atwork", 
        "access_endpoint": "a86e83ac", 
        "website_endpoint": "85df0e64", 
        "expire_time": "9990111",
        "client_id": "test1011"
    }
}*/
module.exports = {
	getContact,
	validateUserTicket,
	getPermanentCode
};